import os
import shutil

root = os.path.dirname(os.path.abspath(__file__))

def create_script_dirs():
    """创建scripts目录和子目录"""
    # 创建scripts目录
    scripts_dir = os.path.join(root, "scripts")
    if not os.path.exists(scripts_dir):
        os.makedirs(scripts_dir)
    
    # 创建python子目录
    python_dir = os.path.join(scripts_dir, "python")
    if not os.path.exists(python_dir):
        os.makedirs(python_dir)
    
    # 创建shell子目录
    shell_dir = os.path.join(scripts_dir, "shell")
    if not os.path.exists(shell_dir):
        os.makedirs(shell_dir)
    
    # 创建cmd子目录
    cmd_dir = os.path.join(scripts_dir, "cmd")
    if not os.path.exists(cmd_dir):
        os.makedirs(cmd_dir)
    
    # 创建docker子目录
    docker_dir = os.path.join(scripts_dir, "docker")
    if not os.path.exists(docker_dir):
        os.makedirs(docker_dir)
    
    return scripts_dir, python_dir, shell_dir, cmd_dir, docker_dir

def move_scripts():
    """移动脚本文件到相应目录"""
    scripts_dir, python_dir, shell_dir, cmd_dir, docker_dir = create_script_dirs()
    
    # 定义Python脚本文件
    python_scripts = [
        "fix_encoding.py",
        "fix_string_errors.py",
        "fix_login_handler.py",
        "fix_all_modules.py",
        "fix_all_gate_server_files.py",
        "fix_all_encoding_issues.py",
        "final_fix.py",
        "delete_problematic_lines.py",
        "create_main_classes.py",
        "comprehensive_fix.py",
        "cleanup_old_packages.py",
        "batch_recreate_more_files.py",
        "batch_recreate_java_files.py",
        "fix_test_client.py",
        "final_cleanup.py",
        "organize_project.py",
        "ultimate_fix.py"
    ]
    
    # 定义CMD脚本文件
    cmd_scripts = [
        "start-all.bat",
        "start-test-client.bat",
        "start-scene-server.bat",
        "start-login-server.bat",
        "start-login-server-simple.bat",
        "start-gate-server.bat",
        "start-central-server.bat",
        "start-balance-server.bat",
        "run-integration-tests.bat"
    ]
    
    # 移动Python脚本
    for script in python_scripts:
        src_path = os.path.join(root, script)
        if os.path.exists(src_path):
            dst_path = os.path.join(python_dir, script)
            shutil.move(src_path, dst_path)
            print(f"移动Python脚本: {script} -> scripts/python/")
    
    # 移动CMD脚本
    for script in cmd_scripts:
        src_path = os.path.join(root, script)
        if os.path.exists(src_path):
            dst_path = os.path.join(cmd_dir, script)
            shutil.move(src_path, dst_path)
            print(f"移动CMD脚本: {script} -> scripts/cmd/")

def move_src_to_scene_server():
    """将src文件夹内容移动到scene-server模块"""
    src_main = os.path.join(root, "src", "main", "java")
    scene_server_main = os.path.join(root, "scene-server", "src", "main", "java")
    
    if os.path.exists(src_main) and os.path.exists(scene_server_main):
        # 获取src目录下的文件
        for item in os.listdir(src_main):
            if item == "com":  # 只移动com目录
                src_com = os.path.join(src_main, item)
                dst_com = os.path.join(scene_server_main, item)
                
                # 如果目标目录已存在，则合并
                if os.path.exists(dst_com):
                    for root_item in os.listdir(src_com):
                        src_root_item = os.path.join(src_com, root_item)
                        dst_root_item = os.path.join(dst_com, root_item)
                        
                        if os.path.isdir(src_root_item):
                            if not os.path.exists(dst_root_item):
                                shutil.move(src_root_item, dst_root_item)
                                print(f"移动目录: src/main/java/com/{root_item} -> scene-server/")
                        else:
                            print(f"目录已存在，跳过: {root_item}")
                        # 移动文件
                        for file_item in os.listdir(src_root_item) if os.path.isdir(src_root_item) else []:
                            src_file = os.path.join(src_root_item, file_item)
                            dst_file = os.path.join(dst_root_item, file_item)
                            if os.path.isfile(src_file):
                                shutil.move(src_file, dst_file)
                                print(f"移动文件: {file_item}")
                else:
                    shutil.move(src_com, dst_com)
                    print(f"移动目录: src/main/java/com -> scene-server/")
    
    # 检查是否可以删除src目录
    try:
        os.rmdir(os.path.join(root, "src", "main", "java", "com"))
        os.rmdir(os.path.join(root, "src", "main", "java"))
        os.rmdir(os.path.join(root, "src", "main"))
        os.rmdir(os.path.join(root, "src"))
        print("已删除空的src目录")
    except:
        print("src目录不为空，保留")

def create_shell_scripts():
    """创建必要的shell脚本"""
    scripts_dir, _, shell_dir, _, docker_dir = create_script_dirs()
    
    # 创建build.sh - 编译脚本
    build_sh = """#!/bin/bash
# 编译所有模块
echo "开始编译Java Last War项目..."
mvn clean package -DskipTests
if [ $? -eq 0 ]; then
    echo "编译成功！"
else
    echo "编译失败！"
    exit 1
fi
"""
    
    with open(os.path.join(shell_dir, "build.sh"), "w") as f:
        f.write(build_sh)
    
    # 创建start-all.sh - 启动所有服务脚本
    start_all_sh = """#!/bin/bash
# 启动所有服务器服务
echo "启动所有服务器..."

# 后台启动各个服务器
nohup java -jar gate-server/target/gate-server-1.0.0.jar --spring.profiles.active=dev > logs/gate-server.log 2>&1 &
nohup java -jar scene-server/target/scene-server-1.0.0.jar --spring.profiles.active=dev > logs/scene-server.log 2>&1 &
nohup java -jar login-server/target/login-server-1.0.0.jar --spring.profiles.active=dev > logs/login-server.log 2>&1 &
nohup java -jar central-server/target/central-server-1.0.0.jar --spring.profiles.active=dev > logs/central-server.log 2>&1 &
nohup java -jar balance-server/target/balance-server-1.0.0.jar --spring.profiles.active=dev > logs/balance-server.log 2>&1 &

echo "所有服务器已启动，使用以下命令查看状态："
echo "ps -ef | grep java"
"""
    
    with open(os.path.join(shell_dir, "start-all.sh"), "w") as f:
        f.write(start_all_sh)
    
    # 创建stop-all.sh - 停止所有服务脚本
    stop_all_sh = """#!/bin/bash
# 停止所有服务器服务
echo "停止所有服务器..."

# 查找并终止Java进程
pkill -f "gate-server-1.0.0.jar"
pkill -f "scene-server-1.0.0.jar"
pkill -f "login-server-1.0.0.jar"
pkill -f "central-server-1.0.0.jar"
pkill -f "balance-server-1.0.0.jar"

echo "所有服务器已停止"
"""
    
    with open(os.path.join(shell_dir, "stop-all.sh"), "w") as f:
        f.write(stop_all_sh)
    
    # 设置脚本权限
    os.chmod(os.path.join(shell_dir, "build.sh"), 0o755)
    os.chmod(os.path.join(shell_dir, "start-all.sh"), 0o755)
    os.chmod(os.path.join(shell_dir, "stop-all.sh"), 0o755)
    
    print("已创建shell脚本")

def create_docker_files():
    """创建Docker配置文件"""
    _, _, _, _, docker_dir = create_script_dirs()
    
    # 创建Dockerfile
    dockerfile = """# 使用Java 21作为基础镜像
FROM openjdk:21-jre-slim

# 设置工作目录
WORKDIR /app

# 创建日志目录
RUN mkdir -p /app/logs

# 复制所有jar包
COPY gate-server/target/gate-server-1.0.0.jar .
COPY scene-server/target/scene-server-1.0.0.jar .
COPY login-server/target/login-server-1.0.0.jar .
COPY central-server/target/central-server-1.0.0.jar .
COPY balance-server/target/balance-server-1.0.0.jar .

# 暴露端口
EXPOSE 8081 8082 8083 8084 8085

# 启动脚本
CMD ["./start-all.sh"]
"""
    
    with open(os.path.join(docker_dir, "Dockerfile"), "w") as f:
        f.write(dockerfile)
    
    # 创建docker-compose.yml
    docker_compose = """version: '3'
services:
  gate-server:
    build: .
    ports:
      - "8081:8081"
    volumes:
      - ./logs:/app/logs
    command: ["java", "-jar", "gate-server-1.0.0.jar"]
    
  scene-server:
    build: .
    ports:
      - "8082:8082"
    volumes:
      - ./logs:/app/logs
    command: ["java", "-jar", "scene-server-1.0.0.jar"]
    
  login-server:
    build: .
    ports:
      - "8083:8083"
    volumes:
      - ./logs:/app/logs
    command: ["java", "-jar", "login-server-1.0.0.jar"]
    
  central-server:
    build: .
    ports:
      - "8084:8084"
    volumes:
      - ./logs:/app/logs
    command: ["java", "-jar", "central-server-1.0.0.jar"]
    
  balance-server:
    build: .
    ports:
      - "8085:8085"
    volumes:
      - ./logs:/app/logs
    command: ["java", "-jar", "balance-server-1.0.0.jar"]
"""
    
    with open(os.path.join(docker_dir, "docker-compose.yml"), "w") as f:
        f.write(docker_compose)
    
    print("已创建Docker配置文件")

def main():
    print("🗂 组织项目文件...")
    
    # 1. 移动脚本文件
    print("\n1. 整理脚本文件...")
    move_scripts()
    
    # 2. 移动src内容到scene-server
    print("\n2. 移动src内容到scene-server...")
    move_src_to_scene_server()
    
    # 3. 创建shell脚本
    print("\n3. 创建shell脚本...")
    create_shell_scripts()
    
    # 4. 创建Docker文件
    print("\n4. 创建Docker配置文件...")
    create_docker_files()
    
    print("\n✅ 项目组织完成！")

if __name__ == "__main__":
    main()